package com.panshi.service.impl;

import com.panshi.mapper.IEmployeeMapper;
import com.panshi.pojo.Employee;
import com.panshi.service.IEmployeeService;
import com.panshi.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    IEmployeeMapper iEmployeeMapper;

    @Autowired
    RedisUtil redisUtil;


    @Override
    public void save(Employee employee) {
        iEmployeeMapper.save(employee);
//        插入更新數據
        updateRedis();
    }

    @Override
    public void update(Employee employee) {
        iEmployeeMapper.update(employee);
//        修改數據庫數據更新
        updateRedis();
    }

    @Override
    public Collection<Employee> getAll() {

//      看緩存中是否有數據  從redis中拿
//        redisUtil.lSet("empList",iEmployeeMapper.getAll());
        Collection<Employee> empList = (Collection<Employee>) redisUtil.lGetIndex("empList", 0);
//        如果緩存中存在元素 返迴緩存數據
        if (empList != null) {
            System.out.println("緩存數據：" + empList);
            return empList;
        }

//            更新緩存
        System.out.println("數據庫數據：" + iEmployeeMapper.getAll());
        redisUtil.lSet("empList", iEmployeeMapper.getAll());
        return iEmployeeMapper.getAll();

    }

    @Override
    public Employee getEmployeeById(Integer id) {
        Collection<Employee> empList = (Collection<Employee>) redisUtil.lGetIndex("empList", 0);
        if (empList != null) {
            for (Employee e : empList) {
                if (e.getEmpId() == id) {
                    System.out.println("緩存對象emp：" + e);
                    return e;
                }
            }
        }
        System.out.println("數據庫emp：" + iEmployeeMapper.getEmployeeById(id));
        updateRedis();
        return iEmployeeMapper.getEmployeeById(id);
    }

    @Override
    public void delete(Integer id) {
        iEmployeeMapper.delete(id);
//        刪除更新redis
        updateRedis();
    }

    //    更新emp數據
    @Override
    public void updateRedis() {
        redisUtil.del("empList");
        redisUtil.lSet("empList", iEmployeeMapper.getAll());
    }

}
